package io.jee.runshan.filter;

import io.jee.runshan.domain.Member;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class RoleFilter extends BaseFilter {
	private static Set<String> unchecked = new HashSet<String>();
	private static final String LOGIN_PAGE = "/login";
	private static final String resource = "/static";
	private static final String upload = "/upload";
	private static final String web = "/web";

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		HttpSession session = request.getSession();
		Member member = (Member) session.getAttribute("CURRENT_LOGINED_MEMBER");
		String requestUrl = request.getServletPath();
		SYSTEM_BASE_PATH = request.getScheme() + "://"+ request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
		
		if (member != null) {
			chain.doFilter(request, response);
		} else if (unchecked.contains(requestUrl)) {
			chain.doFilter(request, response);
		} else if (requestUrl.startsWith(resource)) { // 静态资源放过
			chain.doFilter(request, response);
		} else if (requestUrl.startsWith(upload)) { // 静态资源放过
			chain.doFilter(request, response);
		} else if (requestUrl.startsWith(web)) { // web资源放过
			chain.doFilter(request, response);
		} else {
			response.sendRedirect(SYSTEM_BASE_PATH + LOGIN_PAGE);
		}
	}
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		unchecked.add("/login");
		unchecked.add("/valiCode");
		unchecked.add("/weixin/receive");
	}

}
